package service

import (
	"KD_web/go/dao"
	"KD_web/go/entity"
	"KD_web/go/errors"
	"encoding/json"
	"gorm.io/gorm"
)

func GetTablesByUserId(userId string) (tableList []*entity.Table, err error) {
	if err := dao.SqlSession.Where("userId = ? AND del_status != ?", userId, 1).Find(&tableList).Error; err != nil {
		return nil, errors.ErrTableErr
	}
	return tableList, nil
}

func CreateTableWithId(table *entity.Table) (err error) {
	// 校验是否为json格式
	if !json.Valid([]byte(table.TableData)) {
		return errors.ErrJsonFormat
	}
	userId := table.UserId
	var user *entity.User
	// 校验用户是否存在
	if err := dao.SqlSession.Where("id = ?", userId).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.ErrUsrNotFound
		}
		return err
	}

	if err := dao.SqlSession.Create(table).Error; err != nil {
		return err
	}
	return nil
}

func DeleteTableById(id string) (err error) {
	// 查询是否存在表
	if err := dao.SqlSession.Where("id = ?", id).First(&entity.Table{}).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.ErrTableErr
		}
		return err
	}
	// 逻辑删除
	if err := dao.SqlSession.Model(&entity.Table{}).Where("id = ?", id).Update("del_status", 1).Error; err != nil {
		return err
	}
	return nil
}
